import 'dart:developer' as developer;
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'api_service.dart';
import 'dio_client.dart';

class AuthService {
  static const String _tokenKey = 'auth_token';
  static const String _lastDocIdKey = 'last_document_id';

  /// 获取配置好的 Dio 客户端
  static Dio get _dio => DioClient.getDio(
        allowBadCertificates: ApiService.allowBadCertificates,
      );

  /// 登录
  static Future<String> login(String username, String password) async {
    final url = '${ApiService.baseUrl}/user/login';

    developer.log('🔐 Login Request: POST $url', name: 'Auth');
    developer.log('📦 Request Body: username=$username', name: 'Auth');

    try {
      final response = await _dio.post(
        url,
        data: {
          'username': username,
          'password': password,
        },
        options: Options(
          headers: {
            'Content-Type': 'application/json',
          },
        ),
      );

      developer.log('✅ Login Response: ${response.statusCode}', name: 'Auth');
      developer.log('📥 Response Body: ${response.data}', name: 'Auth');

      if (response.statusCode == 200) {
        final jsonData = response.data;

        if (jsonData['code'] == 200) {
          final token = jsonData['data']['token'] as String;
          await saveToken(token);
          return token;
        } else {
          throw Exception(jsonData['message'] ?? '登录失败');
        }
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } on DioException catch (e) {
      developer.log('❌ Login DioError: ${e.message}', name: 'Auth');
      developer.log('❌ Error Type: ${e.type}', name: 'Auth');
      if (e.response != null) {
        developer.log('❌ Response: ${e.response?.statusCode} - ${e.response?.data}', name: 'Auth');
      }
      throw Exception('登录异常: ${e.message}');
    } catch (e) {
      developer.log('❌ Login Error: $e', name: 'Auth');
      throw Exception('登录异常: $e');
    }
  }

  /// 保存 token
  static Future<void> saveToken(String token) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tokenKey, token);
    developer.log('💾 Token saved successfully', name: 'Auth');
  }

  /// 获取 token
  static Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_tokenKey);
  }

  /// 清除 token
  static Future<void> clearToken() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_tokenKey);
    developer.log('🗑️ Token cleared', name: 'Auth');
  }

  /// 检查是否已登录
  static Future<bool> isLoggedIn() async {
    final token = await getToken();
    return token != null && token.isNotEmpty;
  }

  /// 保存上次打开的文档ID（全局）
  static Future<void> saveLastDocumentId(String docId) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_lastDocIdKey, docId);
    developer.log('💾 Saved last document ID: $docId', name: 'Auth');
  }

  /// 获取上次打开的文档ID（全局）
  static Future<String?> getLastDocumentId() async {
    final prefs = await SharedPreferences.getInstance();
    final docId = prefs.getString(_lastDocIdKey);
    developer.log('📖 Retrieved last document ID: $docId', name: 'Auth');
    return docId;
  }

  /// 清除上次打开的文档ID
  static Future<void> clearLastDocumentId() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_lastDocIdKey);
  }
}
